package master

import (
	"awesomeTask/application/client"
	"awesomeTask/application/timer"
	"awesomeTask/application/variable"
	"awesomeTask/application/vote"
	awesomeTask "awesomeTask/commom"
	"awesomeTask/commom/MessageHelper"
	"awesomeTask/commom/timeHelper"
	"awesomeTask/config"
	"awesomeTask/system/helper"
	"awesomeTask/system/kernel"
	"net"
)

const TABLE_NAME = "t_master_register"

type master interface {
	FindMaster()
	RegisterMaster()
}

type MasterInstance struct {
	IpAddress string
	Port      int
}

func (master MasterInstance) FindMaster() {
	if client.ServerCon != nil {
		return
	}
	variable.ServerConnections.Range(func(key, value interface{}) bool {
		MessageHelper.SendEvent(variable.ON_ASK_FOR_MASTER, make(map[string]interface{}), value.(net.Conn))
		return true
	})
	timer.SetTimeOut(func() {
		if client.ServerCon == nil {
			voteObj := vote.VoteHandler{}
			voteObj.Launch()
		}
	}, timer.Second*10)
}

/**
尝试注册为主节点
*/
func (master MasterInstance) TryToBeMaster() bool {
	res := awesomeTask.BeginTransaction(false, func() bool {
		registerInfo := awesomeTask.Query("select * from " + TABLE_NAME + " limit 1")
		if len(registerInfo) == 0 {
			data := make(map[string]interface{})
			data["unique_id"] = config.GetConfigByKey("uniqueId")
			data["register_time"] = timeHelper.Now()
			data["updated_at"] = timeHelper.Now()
			data["ipaddress"] = config.GetConfigByKey("listenIpAddress")
			data["port"] = config.GetConfigByKey("listenPort")
			data["id"] = 1
			awesomeTask.Insert(TABLE_NAME, data)
			return true
		} else {
			if registerInfo[0]["unique_id"].(string) == config.GetConfigByKey("uniqueId") {
				data := make(map[string]interface{})
				data["unique_id"] = config.GetConfigByKey("uniqueId")
				data["register_time"] = timeHelper.Now()
				data["updated_at"] = timeHelper.Now()
				data["ipaddress"] = config.GetConfigByKey("listenIpAddress")
				data["port"] = config.GetConfigByKey("listenPort")
				data["id"] = 1
				awesomeTask.Update(TABLE_NAME, data, "where id=?", 1)
				return true
			} else {
				if timeHelper.NowInt()-timeHelper.TimeStringParseTimeStamp(registerInfo[0]["register_time"].(string)) > variable.RegisterTick+2 {
					data := make(map[string]interface{})
					data["unique_id"] = config.GetConfigByKey("uniqueId")
					data["register_time"] = timeHelper.Now()
					data["updated_at"] = timeHelper.Now()
					data["ipaddress"] = config.GetConfigByKey("listenIpAddress")
					data["port"] = config.GetConfigByKey("listenPort")
					data["id"] = 1
					awesomeTask.Update(TABLE_NAME, data, "where id=?", 1)
					return true
				}
				return false
			}
		}
	})
	return res
}
func (master MasterInstance) RegisterMaster() {
	if variable.IsMaster == false {
		return
	}
	awesomeTask.BeginTransaction(false, func() bool {
		registerInfo := awesomeTask.Query("select * from " + TABLE_NAME + " limit 1")
		if len(registerInfo) == 0 {
			data := make(map[string]interface{})
			data["unique_id"] = config.GetConfigByKey("uniqueId")
			data["register_time"] = timeHelper.Now()
			data["updated_at"] = timeHelper.Now()
			data["ipaddress"] = config.GetConfigByKey("listenIpAddress")
			data["port"] = config.GetConfigByKey("listenPort")
			helper.PrintJson(data)
			awesomeTask.Insert(TABLE_NAME, data)
		} else {
			data := registerInfo[0]
			helper.PrintJson(data)
			if data["unique_id"].(string) == config.GetConfigByKey("uniqueId").(string) {
				data["unique_id"] = config.GetConfigByKey("uniqueId")
				data["register_time"] = timeHelper.Now()
				data["updated_at"] = timeHelper.Now()
				data["ipaddress"] = config.GetConfigByKey("listenIpAddress")
				data["port"] = config.GetConfigByKey("listenPort")
				awesomeTask.Update(TABLE_NAME, data, "where id=?", data["id"])
				return true
			}
			if timeHelper.TimeStringParseTimeStamp(data["updated_at"].(string))+60 < timeHelper.NowInt() {
				data["unique_id"] = config.GetConfigByKey("uniqueId")
				data["register_time"] = timeHelper.Now()
				data["updated_at"] = timeHelper.Now()
				data["ipaddress"] = config.GetConfigByKey("listenIpAddress")
				data["port"] = config.GetConfigByKey("listenPort")
				awesomeTask.Update(TABLE_NAME, data, "where id=?", data["id"])
				variable.IsMaster = true
				return true
			}

		}
		return true
	})
}

func GetMasterObj() MasterInstance {
	ioc := kernel.GetIocInstance()
	return ioc.GetInstanceOrCreate("master").(MasterInstance)
}
